package org.kfive.nova.io.bio;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 16-3-8
 * Time: 下午10:19
 * To change this template use File | Settings | File Templates.
 */
public class SocketServerApplication {

    private static Logger LOG = Logger.getLogger(SocketServerApplication.class);

    public static ServerSocket serverSocket;
    /**
     * SocketServerApplication启动入口
     * @param port 端口
     */
    public static void run(int port) throws IOException{

        serverSocket = new ServerSocket(port);
        Socket socket = serverSocket.accept();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
            String line;
            while(true){
                line = reader.readLine();
                if("bye".equals(line)){
                    LOG.info("Socket Server stoping...");
                    break;
                }
                printWriter.write(line);

            }

        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }finally {
            socket.close();
            serverSocket.close();
        }

    }

    public static void main(String[] args) {

        try {
            SocketServerApplication.run(8080);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }
}
